import React, { useState, useEffect } from 'react';
import { View, Text, Image, Video } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { Toast, Divider, Button } from '@nutui/nutui-react-taro';
import { IconFont } from '@nutui/icons-react-taro';
import { getPostDetail, likePost, unlikePost } from '../../services/post';
import './index.scss';

const Detail: React.FC = () => {
  const router = useRouter();
  const { id } = router.params;
  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  useEffect(() => {
    if (id) {
      fetchPostDetail(Number(id));
    }
  }, [id]);

  const fetchPostDetail = async (postId: number) => {
    try {
      setLoading(true);
      const response = await getPostDetail(postId);
      setDetail(response);
      setLiked(response.isLiked || false);
      setLikeCount(response.likeCount || 0);
    } catch (error) {
      setToastMessage(error.message || '获取详情失败');
      setShowToast(true);
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async () => {
    try {
      if (liked) {
        await unlikePost(Number(id));
        setLiked(false);
        setLikeCount(prev => prev - 1);
      } else {
        await likePost(Number(id));
        setLiked(true);
        setLikeCount(prev => prev + 1);
      }
    } catch (error) {
      setToastMessage(error.message || '操作失败');
      setShowToast(true);
    }
  };

  const formatDate = (dateString?: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  if (loading) {
    return (
      <View className="detail-loading">
        <Text>加载中...</Text>
      </View>
    );
  }

  if (!detail) {
    return (
      <View className="detail-error">
        <Text>内容不存在或已被删除</Text>
        <Button 
          type="primary"
          onClick={() => Taro.navigateBack()}
          className="back-button"
        >
          返回
        </Button>
      </View>
    );
  }

  return (
    <View className="detail-container">
      <View className="detail-header">
        <Text className="detail-title">{detail.title}</Text>
        <View className="detail-author-info">
          <Image className="author-avatar" src={detail.author?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'} />
          <View className="author-name-time">
            <Text className="author-name">{detail.author?.nickname}</Text>
            <Text className="publish-time">{formatDate(detail.createdAt)}</Text>
          </View>
        </View>
      </View>

      <View className="detail-content">
        <Text className="content-text">{detail.content}</Text>
        
        {detail.images && detail.images.length > 0 && (
          <View className="image-container">
            {detail.images.map((img, index) => (
              <Image 
                key={index} 
                className="content-image" 
                src={img} 
                mode="widthFix"
                onClick={() => {
                  Taro.previewImage({
                    urls: detail.images,
                    current: img
                  });
                }}
              />
            ))}
          </View>
        )}
        
        {detail.video && (
          <Video 
            className="content-video"
            src={detail.video}
            controls
            showFullscreenBtn
          />
        )}
      </View>

      <Divider />
      
      <View className="detail-footer">
        <View 
          className={`action-item ${liked ? 'liked' : ''}`} 
          onClick={handleLike}
        >
          <IconFont name={liked ? "heart-fill" : "heart"} />
          <Text>{likeCount} 赞</Text>
        </View>
        
        <View className="action-item">
          <IconFont name="message" />
          <Text>{detail.commentCount || 0} 评论</Text>
        </View>
      </View>
      
      <Toast
        visible={showToast}
        content={toastMessage}
        onClose={() => setShowToast(false)}
        type="warn"
        duration={2000}
      />
    </View>
  );
};

export default Detail;
